前篇文章將官方範例的寫法寫上 Spring,接著我們要將 LightsPlugin 在 Spring 上呈現
首先我們要建立一個 LightModel,這個Model會用來存放指定的Light的資訊,包括了id、name、isOn
接著輸入以下的程式碼,其實就是將需要的結構用一個 Class包裝
public class LightModel {
private final int id;
private final String name;
private boolean isOn;
public LightModel(int id, String name, boolean isOn) {
this.id = id;
this.name = name;
this.isOn = isOn;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public boolean isOn() {
return isOn;
}
public void setIsOn(boolean isOn) {
this.isOn = isOn;
}
}
接著是 Plugin 的部分,這裡就只要將官方的程式碼複製貼上,就大功告成囉~
public class LightsPlugin {
// Mock data for the lights
private final Map<Integer, LightModel> lights = new HashMap<>();
public LightsPlugin() {
lights.put(1, new LightModel(1, "Table Lamp", false));
lights.put(2, new LightModel(2, "Porch light", false));
lights.put(3, new LightModel(3, "Chandelier", true));
}
@DefineKernelFunction(name = "get_lights", description = "Gets a list of lights and their current state")
public List<LightModel> getLights() {
System.out.println("Getting lights");
return new ArrayList<>(lights.values());
}
@DefineKernelFunction(name = "change_state", description = "Changes the state of the light")
public LightModel changeState(
@KernelFunctionParameter(name = "id", description = "The ID of the light to change") int id,
@KernelFunctionParameter(name = "isOn", description = "The new state of the light") boolean isOn) {
System.out.println("Changing light " + id + " " + isOn);
if (!lights.containsKey(id)) {
throw new IllegalArgumentException("Light not found");
}
lights.get(id).setIsOn(isOn);
return lights.get(id);
}
}
這個部分要將剛剛建立的 plugin 加進來,這樣就可以讓 AI 辨識這個功能
KernelPlugin lightPlugin = KernelPluginFactory.createFromObject(new LightPlugin(),
"LightsPlugin");
kernel = Kernel.builder()
.withAIService(ChatCompletionService.class, chatCompletionService)
.withPlugin(lightPlugin)
.build();
ContextVariableTypes
.addGlobalConverter(
ContextVariableTypeConverter.builder(LightModel.class)
.toPromptString(new Gson()::toJson)
.build());